import { Component, Injector } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LayoutElement } from './layout-element';
import { IToolBarItem, LayoutEditorHelper } from './layout-editor-helper';

@Component({
    templateUrl: './select-child-modal.component.html'
})
export class SelectChildModalComponent extends AppComponentBase {

    callback: (item: LayoutElement)=>void;
    item:LayoutElement;

    ctrl: number = 0;
    options: IToolBarItem[] =[];
    saving = false;

    constructor(
        public bsModalRef: BsModalRef,
        injector: Injector
    ) {
        super(injector);
    }


    shown(item: LayoutElement) {
        this.item = item;
        let items = this.item.editor.contentItems.concat(this.item.editor.layoutItems);
        this.options = item.allowedChildLabels.map(t=> items.find(tt=>tt.contentTypeLabel === t));
    }

    close(): void {
        this.bsModalRef.hide();
    }

    save() {
        if(this.item){
            this.saving = true;

            if (this.options.length > this.ctrl) {
                let selectedItem = this.options[this.ctrl];
                let child = LayoutEditorHelper.getDragingItem(selectedItem, this.item.editor);
                child.isDropingItem = false;
                this.item.addToChildren(child);
                this.callback(child);
            }

            this.saving = false;
        }
        this.close();
    }
}
